import { PdfJs, Spinner, Store, StoreHandler } from "../../core";

import AttachmentLoader from "./AttachmentLoader";
import StoreProps from "./StoreProps";
import { FC, useEffect, useState } from "react";

const AttachmentListWithStore: FC<{
  store: Store<StoreProps>;
}> = ({ store }) => {
  const [currentDoc, setCurrentDoc] = useState(store.get("doc"));

  const handleDocumentChanged: StoreHandler<PdfJs.PdfDocument> = (
    doc: PdfJs.PdfDocument
  ) => {
    setCurrentDoc(doc);
  };

  useEffect(() => {
    store.subscribe("doc", handleDocumentChanged);

    return () => {
      store.unsubscribe("doc", handleDocumentChanged);
    };
  }, []);

  return currentDoc ? (
    <AttachmentLoader doc={currentDoc} />
  ) : (
    <div className="rpv-attachment__loader">
      <Spinner />
    </div>
  );
};

export default AttachmentListWithStore;
